import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt

# 图表生成类
class Chart:
    def __init__(self, chart_display_frame):
        self.chart_display_frame = chart_display_frame

    def plot_pie_chart(self, all_data):
        # 清除之前的图表
        for widget in self.chart_display_frame.winfo_children():
            widget.destroy()

        # 数据处理：获取所有车企的销量
        brand_sales = {}
        for data in all_data:
            brand = data["品牌/车型"].split("/")[0]  # 车企名称
            sale_count = int(data["本月销量"])  # 销量
            if brand in brand_sales:
                brand_sales[brand] += sale_count
            else:
                brand_sales[brand] = sale_count

        # 提取车企和销量数据
        brands = list(brand_sales.keys())
        sales = list(brand_sales.values())

        # 按销量降序排列
        sorted_data = sorted(zip(brands, sales), key=lambda x: x[1], reverse=True)
        brands, sales = zip(*sorted_data)

        # 创建扇形图
        fig = plt.figure(figsize=(12, 12))  # 设定图表大小
        plt.pie(sales, labels=brands, autopct='%1.1f%%', startangle=140)
        plt.title('各车企汽车销量扇形图')

        # 在Tkinter中显示图表
        canvas_agg = FigureCanvasTkAgg(fig, master=self.chart_display_frame)
        canvas_agg.get_tk_widget().pack(pady=10, fill=tk.BOTH, expand=True)
        canvas_agg.draw()

    def plot_bar_chart(self, all_data):
        # 清除之前的图表
        for widget in self.chart_display_frame.winfo_children():
            widget.destroy()

        # 数据处理：获取所有车企的销量
        brand_sales = {}
        for data in all_data:
            brand = data["品牌/车型"].split("/")[0]  # 车企名称
            sale_count = int(data["本月销量"])  # 销量
            if brand in brand_sales:
                brand_sales[brand] += sale_count
            else:
                brand_sales[brand] = sale_count

        # 提取车企和销量数据
        brands = list(brand_sales.keys())
        sales = list(brand_sales.values())

        # 按销量降序排列
        sorted_data = sorted(zip(brands, sales), key=lambda x: x[1])
        brands, sales = zip(*sorted_data)

        # 创建水平柱状图
        fig, ax = plt.subplots(figsize=(10, 6))  # 设定图表大小
        colors = ['skyblue'] * (len(brands) - 5) + ['red'] * 5  # 前五个为红色，其余为天蓝色
        bars = ax.barh(brands, sales, color=colors)  # 创建水平柱状图

        # 在柱子上方添加数值标签
        for bar in bars:
            width = bar.get_width()
            ax.text(width, bar.get_y() + bar.get_height() / 2, f'{width}', va='center', ha='left', fontsize=8)

        # 添加标签和标题
        ax.set_xlabel('销量')
        ax.set_ylabel('车企')
        ax.set_title('各车企汽车销量柱状图')

        # 在Tkinter中显示图表
        canvas_agg = FigureCanvasTkAgg(fig, master=self.chart_display_frame)
        canvas_agg.get_tk_widget().pack(pady=10, fill=tk.BOTH, expand=True)
        canvas_agg.draw()